<?php
/*
 * 系统设置
 */
class GlobalController extends MyClass_Action {
	protected $controller;
	protected $action;
	
	public function init() {
		$this->_user = $this->checkLogin ();
		/* Initialize action controller here */
		$this->controller = $this->getRequest ()->getControllerName ();
		$this->action = $this->getRequest ()->getActionName ();
		
		$this->commonTemplates ();
		
		$this->_smarty->assign ( 'controller', $this->controller );
		$this->_smarty->assign ( 'action', $this->action );
		$this->_smarty->assign ( '_user', $this->_user );
		
		//get database
		$this->getDb ( 'osmdb' );
	}
	
	public function indexAction() {
		try {
			// action body
			$sql = 'select variable,value,readme from crm_settings';
			$result = $this->_dbAdapter->fetchAll ( $sql );
			$this->_smarty->assign ( 'result', $result );
			
			$this->_smarty->display ( $this->controller . '/' . $this->action . '.tpl' );
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	/*
	 * 同步维护脚本
	 */
	public function checkAction() {
		try {
			// action body
			$check=array();
			
			$this->_smarty->assign ( 'check', $check );
			$this->_smarty->display ( $this->controller . '/' . $this->action . '.tpl' );
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
		
		
	public function opAction() {
		try {
			if (! $this->isPost ()) {
				throw new Exception ( '参数错误！' );
			}
			$addResult=$updateResult=0;

			 $p=$this->_request->getPost ();
			 
			 if(!empty($p['add']['variable'])){
			 		$addResult=$this->_dbAdapter->insert('crm_settings',$p['add']); 
			 }
			 unset($p['add']);

			 foreach($p as $key => $value){
			  $result = $this->_dbAdapter->update ( 'crm_settings', array ('value' => trim($value) ), 'variable="' . $key .'"');
			  if ($result)
					$updateResult = 1;
			 }

			 if($addResult || $updateResult){
			 	$this->createSetting();
				$this->feedback ( '保存成功', '成功',  $this->controller.'/index', 'tip', 0 );
			} else {
				throw new Exception ( '保存失败！' );
			}
			 
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	public function createAction() {
		
		try {
			
			$result=$this->createSetting ();
			
			if($result)
				$this->feedback ( "Created Successfully", 'Caution', '', 'tip' );
			else
				throw new Exception ( 'Failure!' );
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	
	}
	private function createSetting() {
		
		try {
			
			$result = $this->_dbAdapter->fetchPairs ( 'select variable,value from crm_settings' );
			
			//写入文件
			// 调用方法
			/*
        	    $file_name=PROJECT_ROOT.$this->_config->dbcache->dir.'/Setting.php';
        	    if(file_exists($file_name))
            		$_setting= include $file_name;
           		 else	
            		throw new Exception ( '配置文件不存在，请先生成配置文件！' );
            	
            */

			$dirname = PROJECT_ROOT . $this->_config->dbcache->dir;
			
			//目录不存在就创建
			if (! file_exists ( $dirname )) {
				@mkdir ( $dirname, 0777 );
				@system ( "chmod 0777 " . $dirname );
			}
			
			$file_name = $dirname . '/Setting.php';
			
			if (! $fp = fopen ( $file_name, "w+" )) {
			return -1;
				//throw new Exception ( '文件打开失败！' );
			}
			
			if (! fwrite ( $fp, "<?php\n return " . var_export ( $result, TRUE ) . ";\n?>" )) {
				fclose ( $fp );
				return -2;
				//throw new Exception ( '文件写入失败！' );
			}
			
			fclose ( $fp );
			//chmod ( $file_name, 0666 );
			
			return true;
		
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	
	}

//////////////////
	public function shopAction() {
		try {
			$count = 40; //pre
    			$curpage = ( int ) $this->_request->getParam ( 'page' );
    			if (! $curpage)
    				$curpage = 1;
    			$offset = ($curpage - 1) * $count;
    			
			$sql='select SQL_CALC_FOUND_ROWS * from crm_shops order by shopid asc '." limit $offset,$count";
			$result = $this->_dbAdapter->fetchAll ( $sql );
			
			 foreach($result as $key => $value){
			 	$result[$key]['addtime']=date('Y-m-d H:i',$value['addtime']);
			 	$result[$key]['disabled']=$value['isdisabled']?'无效':'有效';
			 }
			
			//翻页控制
    			$param ['file'] = '/' . $this->controller . '/' . $this->action;
    			$param ['totalnum'] = $this->_dbAdapter->fetchOne ( 'SELECT FOUND_ROWS()' );
    			$param ['perpagenum'] = $count; // 每页显示的数目
    			$param ['disnum'] = 11; // 取单数显示，当前页停在中间
    			$param ['curpage'] = $curpage; // 当前页码
    			$this->_smarty->assign ( 'allnum', $param ['totalnum'] );
    
    			//	require_once 'MyClass/class.page.php';
    			$page = new MyClass_Page ( $param );
    			//$page->setvar ( array ('gid' => $gradeid,'typeid'=>$typeid) );
    
    			$this->_smarty->assign ( 'page', $page->getNumPage () );
			
			$this->_smarty->assign ( 'result', $result );
			$this->_smarty->display ( $this->controller . '/' . $this->action . '.tpl' );
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	//增加公告
	public function shopaddAction() {
		try {
			
			
			$this->_smarty->display ( $this->controller . '/' . $this->action . '.tpl' );
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	//处理增加公告
	public function opshopaddAction() {
		try {
			if (! $this->isPost ()) {
				throw new Exception ( '参数错误！' );
			}
		
			$p =$this->_request->getPost ();
				$p['addtime']=time();
				if (!isset( $p ['isdisabled'] )) 
				$p ['isdisabled'] = 0;
				
			$result = $this->_dbAdapter->insert ( 'crm_shops', $p );
			if ($result) {
				$this->feedback ( '保存成功', '成功', $this->controller . '/shop' , 'tip', 0 );
			} else {
				throw new Exception ( '增加失败！' );
			}
			
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	
		//修改公告
	public function shopeditAction() {
		try {
			
			$id = ( int ) $this->_request->getParam ( 'shopid' );
			if (! $id)
				throw new Exception ( '参数错误！' );
			
			$sql='select * from crm_shops where shopid=' . $id;
			$result = $this->_dbAdapter->fetchRow ( $sql );
			
			$this->_smarty->assign ( 'result', $result );
			
			$this->_smarty->display ( $this->controller . '/' . $this->action . '.tpl' );
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//处理修改公告
	public function opshopeditAction() {
		try {
			if (! $this->isPost ()) {
				throw new Exception ( '参数错误！' );
			}
		
			$p =$this->_request->getPost ();
				$p['addtime']=time();
				if (!isset( $p ['isdisabled'] )) 
				$p ['isdisabled'] = 0;
				
			$result = $this->_dbAdapter->update ( 'crm_shops', $p, 'shopid=' . $p ['shopid'] );	
			if ($result) {
				$this->feedback ( '保存成功', '成功', $this->controller . '/shop' , 'tip', 0 );
			} else {
				throw new Exception ( '增加失败！' );
			}
			
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	//删除公告
	public function shopdeleteAction() {
		try {
			$id = ( int ) $this->_request->getParam ( 'shopid' );
			if (! $id)
				throw new Exception ( '参数错误！' );
				
			$del_result = $this->_dbAdapter->delete ( 'crm_shops', 'shopid=' . $id);
				if ($del_result) {
				   $this->feedback ( '操作成功,请刷新查看！', '成功',$this->controller . '/shop' , 'tip', 0 );
				} else {
				   throw new Exception ( '操作失败或已经删除，请先刷新查看！' );
						}
		} catch ( Exception $e ) {
			$this->feedback ( $e->getMessage (), 'Caution', 'javascript:window.history.back();', 'warning' );
		}
	}
	
	
	
	//reserve statement as below
	public function noRouteAction() {
		$this->_redirect ( '/' );
	}
	
	public function __call($method, $args) {
		if ('Action' == substr ( $method, - 6 )) {
			$url = '/' . $this->controller . '/index';
			return $this->_redirect ( $url );
		}
		
		throw new Exception ( 'Invalid method' );
		
		// all other methods throw an exception
		throw new Exception ( 'Invalid method "' . $method . '" called' );
	}
}

